﻿using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Eneta.Portal.Common;
using Eneta.Portal.Common.Repository;
using Microsoft.SharePoint;

namespace Eneta.Portal.Profiles.Controls
{
    public class AuthenticatedLogInControl : UserControl
    {
        protected HtmlAnchor profileLink;
        protected Label userNameLabel;
        protected HtmlImage userImage;

        protected HtmlAnchor profileIndicatorLink;
        protected HtmlImage percentImage;

        public override void DataBind()
        {
 	        base.DataBind();

            var user = SPContext.Current.Web.CurrentUser;
            if (user == null)
            {
                Visible = false;
                return;
            }

            var repository = new UserProfileRepository(SPContext.Current.Web);
            var profile = repository.GetUserProfileByUserName(user.LoginName);

            if (profile == null)
            {
                Logger.LogWarning("Cannot find profile for user " + user.LoginName + " (" + user.Name + ")", "LogInControl.OnLoad()");
                Visible = false;
                return;
            }

            profileLink.HRef = "/profile.aspx?ID=" + profile.Id;
            userNameLabel.Text = profile.UserName;

            userImage.Src = profile.UserImage32x32Url;

            var indicatorValue = profile.GetProfileFillmentPercent();
            profileIndicatorLink.HRef = profileLink.HRef;
            profileIndicatorLink.InnerText = "Profiil " + indicatorValue + "% valmis";
            percentImage.Style["width"] = indicatorValue + "%";
            percentImage.Attributes["title"] = profileIndicatorLink.InnerText;
            percentImage.Alt = profileIndicatorLink.InnerText;
        }
    }
}
